package com.itelite.common.util;

import cn.afterturn.easypoi.word.WordExportUtil;
import com.itelite.common.info.WordImageEntity;
import com.itelite.config.WebAppConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

/**
 * @author 沈洋 邮箱:1845973183@qq.com
 * @create 2021/8/11-17:09
 **/
@Slf4j
@SuppressWarnings("unchecked")
public class WordUtils {
    public static void exportWordByImg(String templatePath, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        Assert.notNull(templatePath,"模板路径不能为空");
        Assert.notNull(fileName,"导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"),"word导出请使用docx格式");
        try {
            String userAgent = request.getHeader("user-agent").toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            } else {
                fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
//            log.info("templatePath:"+templatePath);
//            log.info("params:"+String.valueOf(params));
//            http://sywxr.online:8080/
            List<String>  urls  = (List<String>)params.get("imageUrls");

            for (int i = 0; i < urls.size(); i++) {
                WordImageEntity image = new WordImageEntity();
                image.setHeight(150);//设置高度
                image.setWidth(270);//设置宽度
                image.setType(WordImageEntity.Data);//类型
                String imagePath = WebAppConfig.ROOT+urls.get(i);
                File imageFile = new File(imagePath);
                InputStream input = new FileInputStream(imageFile);
                byte[] data = null;
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int numBytesRead = 0;
                while ((numBytesRead = input.read(buf)) != -1) {
                    output.write(buf, 0, numBytesRead);
                }
                data = output.toByteArray();
//                output.close();
//                input.close();
                image.setData(data);
                params.put("imageUrl"+i, image);
            }

            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            String tmpPath = fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            OutputStream out = response.getOutputStream();
            doc.write(out);
            out.close();
            File file = new File(tmpPath);
            if(file.exists()){
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 图片转为byte数组
     *
     */
//    public static byte[] image2byte(String path) throws IOException {
//        byte[] data = null;
//        URL url = null;
//        InputStream input = null;
//        try{
//            url = new URL(path);
//            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
//            httpUrl.connect();
//            httpUrl.getInputStream();
//            input = httpUrl.getInputStream();
//        }catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        byte[] buf = new byte[1024];
//        int numBytesRead = 0;
//        while ((numBytesRead = input.read(buf)) != -1) {
//            output.write(buf, 0, numBytesRead);
//        }
//        data = output.toByteArray();
//        output.close();
//        input.close();
//        return data;
//    }

}
